package jms.customer;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

public class JmsConsumer extends Thread{
	private Connection conn;
	private Session session;
	private MessageConsumer consumer;
	private String name;
	
	public JmsConsumer(String name){
		try {
			Connection conn = JmsConnection.getInstance().createConnection();
			conn.start();
			session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
			Destination destination = session.createQueue("test");
			consumer = session.createConsumer(destination);
			this.name = name;
		} catch (JMSException e) {
			e.printStackTrace();
		}
		
	}
	
	public void consume(){
		DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
		while (true) {
			try {
				TextMessage message = (TextMessage) consumer.receive();
				String text = message.getText();
				if (text.equals("hello0")) {
					Thread.sleep(10000);
				}else {
					Thread.sleep(3000);
				}
				message.acknowledge();
				System.out.println("name:"+name+"\ttext:"+text+"\tack:"+dateFormat.format(new Date()));
			} catch (JMSException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	@Override
	public void run() {
		consume();
	}
	
	public void close(){
		try {
			consumer.close();
			session.close();
			conn.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	
	public static void main(String[] args) {
		String name = "tom";
		for(int i=0;i<3;i++) {
			new JmsConsumer(name+i).start();
		}
	}
	
	
}
